from django.db import transaction
from rest_framework import permissions
from rest_framework.generics import ListAPIView
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SystemLog, Upload
from .serializers import ArticleSerializer, RelateArticleSerialzier
from .models import Article
from .filters import ArticleFilter


class RelateArticleViewSet(ListAPIView):
    queryset = Article.objects.filter(delete=False)
    serializer_class = RelateArticleSerialzier


class ArticleViewSet(CustomModelViewSet):
    '''后台article CRUD操作'''
    permission_classes = [permissions.IsAdminUser]
    queryset = Article.objects.filter(delete=False)
    serializer_class = ArticleSerializer

    def filter_queryset(self, queryset):
        f = ArticleFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                # raise_exception 标志，如果存在验证错误，将会抛出 serializers.ValidationError 异常
                if serializer.is_valid(raise_exception=True):
                    file_id = request.data['thumbnail']
                    upload = Upload.objects.filter(id=file_id).first()
                    if not upload:
                        return response_error('封面图片文件不存在')
                    # 有时您会希望您的视图代码能够在保存实例时注入额外的数据。此额外数据可能包括当前用户,您可以通过在调用 .save() 时包含其他关键字参数来执行此操作
                    serializer.save(user=self.request.user, thumbnail=upload)
                    return response_ok()
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))

    def perform_create(self, serializer):
        super(ArticleViewSet, self).perform_create(serializer)
        instance = serializer.instance
        SystemLog.objects.add_log(self.request.user, SystemLog.INSERT, '新增文章article(id=%s)信息' % instance.id)

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.delete = True
                instance.save()
                SystemLog.objects.add_log(self.request.user, SystemLog.INSERT, '删除文章article(id=%s)信息' % instance.id)
        except Exception as e:
            return response_error(str(e))
        return response_ok()
